//
//  NewDataiewController.m
//  SunXi
//
//  Created by dllo on 15/12/4.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "NewDataiewController.h"
#import "NewpageTableViewCell.h"
@interface NewDataiewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,IChatManagerDelegate>
@property (nonatomic, strong)CoreDataManager *manager;
@property(nonatomic, strong) NSArray *arr;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) UIView *MyView;
@end

@implementation NewDataiewController{
    UITextField *_messField;
    UIButton *_button;
    BOOL _first;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"新消息" object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"yonghu1"] style:UIBarButtonItemStylePlain target:self action:@selector(presentRightMenuViewController:)];
    [self.navigationItem.rightBarButtonItem setTintColor:BUTTONCOLOR];
    SV.BC = [UIColor whiteColor];
    self.navigationItem.title = self.usermane;
    self.MyView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)];
    [SV addSubview:self.MyView];
    self.manager = [CoreDataManager defaults];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createData) name:@"新消息" object:nil];

    [self createData];
    [self initMyTableView];
    [self inittakeValue];
    [self registerForKeyboardNotifications];
    _first = NO;
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];

    if (self.arr.count != 0) {
        NSIndexPath *indexpath =  [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}
/**
 *  查询历史消息
 */
- (void)createData{
//    self.mutableArr = [NSMutableArray array];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"UserMess"];
   
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@",@"user",@"%@"],self.usermane];
    request.predicate = predicate;
   
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"time" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error;
    self.arr = [[self.manager managedObjectContext] executeFetchRequest:request error:&error];


    
    [self.tableView reloadData];
    /**
     *  滚到最后一行
     */
    if (self.arr.count != 0) {
        NSIndexPath *indexpath =  [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    for (UserMess *temp in self.arr) {
        temp.look = @0;
    }
    
    [self.manager saveContext];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewpageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"xiaoxi"];
    if (!cell) {
        cell = [[NewpageTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"xiaoxi"];
    }
    UserMess *model = self.arr[indexPath.row];
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_messField resignFirstResponder];
    
    UserMess *model = self.arr[indexPath.row];
    if ([model.mess hasPrefix:@"SXmovie:"]) {
        NSArray *strArr = [model.mess componentsSeparatedByString:@"网址"];
        NSString *title = [[strArr firstObject] stringByReplacingOccurrencesOfString:@"SXmovie:" withString:@""];
        MVDetailsViewController *deVC = [[MVDetailsViewController alloc]init];
        deVC.str = [strArr lastObject];
        deVC.mytitle = title;
        [self.navigationController pushViewController:deVC animated:YES];
    }else if ([model.mess hasPrefix:@"SXlook:"]) {
        NSArray *strArr = [model.mess componentsSeparatedByString:@"网址"];
        NSString *title = [[strArr firstObject] stringByReplacingOccurrencesOfString:@"SXlook:" withString:@""];
        WebView *webVC = [[WebView alloc]init];
        webVC.url = [strArr lastObject];
        webVC.tittle = title;
        [self.navigationController pushViewController:webVC animated:YES];
    }else if ([model.mess hasPrefix:@"SXradio:"]) {
     
        NSArray *strArr = [model.mess componentsSeparatedByString:@"网址"];
        NSString *title = [[strArr firstObject] stringByReplacingOccurrencesOfString:@"SXradio:" withString:@""];
        NSDictionary *dic = [DyAFnetWorking convertStrToBodyDic:[strArr lastObject]];
        RadioModel *model = [[RadioModel alloc]init];
        model.radioid = dic[@"radio"];
        model.musicUrl = dic[@"url"];
        NSDictionary *dicfir = @{@"uname":dic[@"user"]};
        NSDictionary *dictwo = @{@"userinfo":dicfir};
        model.userinfo = dictwo;
        model.title = title;
        model.coverimg = dic[@"image"];
        RadioplayViewController *playVC = [[RadioplayViewController alloc]init];
        [RadioSavemodel shareSingleton].playlistArr = [NSMutableArray arrayWithObjects:model, nil];
        [RadioSavemodel shareSingleton].playNumber = 0;
        [self.navigationController pushViewController:playVC animated:YES];

        
    }
        
    

    
    
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)presentLeftMenuViewController:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)initMyTableView{
    self.tableView = ({
        UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 104) style:UITableViewStylePlain];
        table.delegate = self;
        table.dataSource = self;
        table;
    });
    [self.MyView addSubview:self.tableView];
    
}
/**
 *  创建发送消息按钮
 */
- (void)inittakeValue{
    self.MyView.backgroundColor = [UIColor colorWithRed:0.892 green:0.895 blue:0.904 alpha:1.000];
    _messField = [[UITextField alloc]initWithFrame:CGRectMake(7, HEIGHT - 99, WIDTH - 55, 25)];
    [self.MyView addSubview:_messField];
    _messField.delegate = self;
    UIView *xian = [[UIView alloc]initWithFrame:CGRectMake(5, HEIGHT - 68, WIDTH - 55, 2)];
    _messField.returnKeyType = UIReturnKeyGo;
    [self.MyView addSubview:xian];
    xian.backgroundColor = BUTTONCOLOR;
    _button = [UIButton buttonWithType:UIButtonTypeSystem];
    _button.frame = CGRectMake(WIDTH - 50, HEIGHT - 96, 40, 25);
    _button.BC = BUTTONCOLOR;
    [_button setTitle:@"发送" forState:0];
    [self.MyView addSubview:_button];
    [_button addTarget:self action:@selector(pushMess) forControlEvents:UIControlEventTouchUpInside];
    [_button setEnabled:NO];
}


//协议
//点击return 触发的方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length > 0) {
        [self pushMess];
    }
    return YES;
}
/**
 *  发送消息
 */
- (void)pushMess{
    
    EMChatText *txtChat = [[EMChatText alloc] initWithText:_messField.text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
    
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.usermane bodies:@[body]];
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    
    EMError *error = nil;
    
    id <IChatManager> chatManager = [[EaseMob sharedInstance] chatManager];
    [chatManager sendMessage:message progress:nil error:&error];
        if (error) {
            UIAlertView * a = [[UIAlertView alloc] initWithTitle:@"error" message:@"发送失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
            [a show];
        }else{
            NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserMess" inManagedObjectContext:self.manager.managedObjectContext];
            UserMess *model = [[UserMess alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
            //赋值
            model.type = @2;
            model.mess = _messField.text;
            model.user = self.usermane;
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval time =[dat timeIntervalSince1970]*1000;
            NSString *str = [NSString stringWithFormat:@"%.0f",time];
            model.time = [NSNumber numberWithDouble:[str doubleValue]];
            model.look = @0;
            [self.manager saveContext];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"新消息" object:nil];
            [_button setEnabled:NO];
        }
    _messField.text = nil;
}
/**
 *  获取键盘高度
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.text.length > 0) {
        [_button setEnabled:YES];
    }else{
        [_button setEnabled:NO];
    }
   
    return YES;
    
}
- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    NSLog(@"keyBoard:%f", keyboardSize.height);  //216
    if (!_first) {
        _first = YES;
        self.tableView.frame = CGRectMake(0, keyboardSize.height, WIDTH, HEIGHT - 40 - keyboardSize.height);
        self.MyView.center = CGPointMake(self.MyView.center.x, self.MyView.center.y - keyboardSize.height);
        if (self.arr.count != 0) {
            NSIndexPath *indexpath =  [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }

    }
}
- (void) keyboardWasHidden:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
    if (_first) {
        self.tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 40);
        _first = NO;
        self.MyView.center = CGPointMake(self.MyView.center.x, self.MyView.center.y + keyboardSize.height);
        if (self.arr.count != 0) {
            NSIndexPath *indexpath =  [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }

    }

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 
*/

@end
